import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import Layout from '../layout/index.vue'
import { useUserStore } from '@/stores/user'
import systemRoutes from './modules/system'
import { storeToRefs } from 'pinia'
import { generateRoutes } from './utils'

// 基础路由
export const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录' }
  },
  // {
  //   path: '/404',
  //   component: () => import('@/views/error/404.vue'),
  //   meta: { title: '404' }
  // },
  {
    path: '/401',
    component: () => import('@/views/error/401.vue'),
    meta: { title: '401' }
  },
  {
    path: '/',
    component: () => import('@/layout/index.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '首页', icon: 'HomeFilled' }
      }
    ]
  },
  // {
  //   path: '/system',
  //   component: () => import('@/layout/index.vue'),
  //   redirect: '/system/dict',
  //   children: [
  //     {
  //       path: 'system/dict',
  //       component: () => import('@/views/system/dict/index.vue'),
  //       meta: { title: '首页', icon: 'HomeFilled' }
  //     }
  //   ]
  // },
]

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes
})

const whiteList = ['/login', '/404', '/401'] // 白名单

// 用于标记路由是否已经动态添加
let hasAddRoutes = false
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  const { token, userInfo, menuList } = storeToRefs(userStore)
  // console.log('路由守卫 token:', token.value)
  // console.log('路由守卫 userInfo:', userInfo.value)

  if (token.value) {
    if (to.path === '/login') {
      next('/')
    } else {
      // 如果没有路由，但有用户信息，直接生成路由
      if (!hasAddRoutes) {
        if (userInfo.value && menuList.value.length) {
          // 使用本地存储的数据生成路由
          const accessRoutes = generateRoutes(menuList.value)
          accessRoutes.forEach(route => {
            router.addRoute(route as any)
          })
          // router.addRoute({
          //   path: '/:pathMatch(.*)*',
          //   redirect: '/404'
          // })
          console.log(accessRoutes, router.getRoutes());
          hasAddRoutes = true
          next({ ...to, replace: true })
        } else {
          try {
            // 获取用户信息
            const hasInfo = await userStore.getInfo()
            console.log('路由守卫获取用户信息结果:', hasInfo)
            console.log('路由守卫更新后的用户信息:', userStore.userInfo)
            if (hasInfo) {
              // 生成动态路由
              const accessRoutes = generateRoutes(menuList.value)
              
              // 添加动态路由
              accessRoutes.forEach(route => {
                router.addRoute(route as any)
              })

              // 添加404路由
              // router.addRoute({
              //   path: '/:pathMatch(.*)*',
              //   redirect: '/404'
              // })

              

              // 标记路由已添加
              hasAddRoutes = true

              // 重定向到目标路由
              next({ ...to, replace: true })
            } else {
              userStore.clearAll()
              hasAddRoutes = false
              next('/login')
            }
          } catch (error) {
            userStore.clearAll()
            hasAddRoutes = false
            next('/login')
          }
        }
      } else {
        console.log("router:", router);
        next()
      }
    }
  } else {
    hasAddRoutes = false
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
}) 
// 路由守卫
// router.beforeEach((to, from, next) => {
//   const userStore = useUserStore()
//   const token = userStore.token

//   if (to.path === '/login') {
//     if (token) {
//       next('/')
//     } else {
//       next()
//     }
//   } else {
//     if (token) {
//       next()
//     } else {
//       next('/login')
//     }
//   }
// })

export default router 